/*
 * @author: sanbao
 * @Date: 2022-07-22 14:21:10
 */
//src/store/index.ts
import { createStore } from 'vuex'
import LoginModel from '../api/login'
import persist from 'vuex-persistedstate'
import {
  setToken,
  getToken,
} from '../utils/auth'
const store = createStore({
  state: {
    token: getToken() ? getToken() : '',
    isCollapse: false,
    tagviewlist: [{ name: "个人中心", path: 'profile' }]
  },
  getters: {},
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    leftnav(state) {
      state.isCollapse = !state.isCollapse
    },
    tagview(state, tagview: object) {
      let index = state.tagviewlist.findIndex(v => v.path == tagview.path)
      if (index == -1) {
        state.tagviewlist.push(tagview)
      }
    },
    deltagview(state, index) {
      state.tagviewlist.splice(index, 1)
    },
    youce(state, index) {
      state.tagviewlist.splice(index + 1, 9999)
    },
    guanbi(state, index) {
      state.tagviewlist = state.tagviewlist.splice(index,1)
    }
  },
  actions: {
    // 登陆
    handelloginbutton({ commit }, lognglist) {
      return new Promise(async (resolve, reject) => {
        try {
          const response = await LoginModel.postlogin(lognglist)
          if (response.data.success == true) {
            const { token } = response.data.data
            commit("setToken", token)
          }
          resolve(response)
        } catch (err) {
          reject(err)
        }
      })
    }
  },
  modules: {},
  plugins: [
    new persist({
      storage: window.localStorage
    })
  ],
})

export default store

